import React , { useState, useMemo,useEffect,useRef  } from 'react'
import { Tabs ,Col, Row, Button ,Checkbox, Select, DatePicker, Input, Space, Modal , Form, Radio, InputNumber , message} from 'antd';
import type { TabsProps } from 'antd';
import PatientGroup from './tabs/PatientGroup';
import History from './tabs/History';
import dayjs from 'dayjs'; // 日期操作的类库
import { addPatient } from '../../api/patient';


import style from './style.module.scss'

const Patient = ()=>{



    const [ sideWidth, setSideWidth ] = useState(300);
    const [ showAdd, setShowAdd] = useState(false);
    const [ inputBl, setInputBl] = useState(true);
    const [ hasPrefix,  sethasPrefix] = useState(true);
    const [ hasDate, sethasDate ] = useState(true);
    const [ startNum, setStartNum ] = useState( Math.ceil(Math.random()*10000)+1 );
    const [ showSetup, setShowSetup ] = useState(false)
    const [ formRef ] = Form.useForm();
    
    
    const prefix = 'QF' ;//  病历号的前缀
    const dateStr = dayjs().format('YYYYMMDD');
    const countNum = useMemo(()=>{
        return `${startNum}`.padStart(5,'0');
    },[startNum])

    const tabItems:TabsProps['items'] = [
        { 
            key: '1',
            label: '患者分组',
            children: <PatientGroup />
         },
         { 
            key: '2',
            label: '最近查看',
            children: <History />
         }
    ]
    const createOption = [
        {
            label:'创建时间',
            value: '创建时间',
        },
        {
            label:'上次就诊时间',
            value: '上次就诊时间',
        }
    ]

    // 新增患者
    const handleAdd = async ()=>{
        // 先完成表单的校验
        try{
            await formRef.validateFields();
            const res = formRef.getFieldsValue();
            console.log('表单收集到的内容', res)
            const addRes = await addPatient({
                ...res,
                createdAt: res.createdAt.format('YYYY-MM-DD HH:mm:ss'),
                birth: res.birth.format('YYYY-MM-DD HH:mm:ss'),
                avatar: photo
            })
            console.log("addRes",addRes)
            message.success('添加成功');
            setShowAdd(false);     // 关闭弹窗
            formRef.resetFields(); // 重置表单
        } catch(e){
            message.warning('请检查要填写的内容')
        }
       
    }
    // 设置一个初始化的病历号
    useEffect(()=>{
        formRef.setFieldValue('docNo', `${hasPrefix? prefix : ''}${hasDate?dateStr:'' }${countNum}`)
    },[])


    // 拍照的业务流程
    const [ showPhoto,setShowPhoto ] = useState(false);
    const [ disConfirm, setDisConfirm ] = useState(true);
    const [ photo, setPhoto ] = useState('')
    const photoRef = useRef<any>();
    const canvasRef = useRef<any>();

    // 初始化相机
    const initCamera = ()=>{
        navigator.mediaDevices.getUserMedia({
            video: true,  // 获取摄像头
            audio: false, // 获取🎤
        })
            .then(function (stream) {
                /* 使用这个 stream stream */
                setShowPhoto(true)
                // 使用视频

                var video = photoRef.current;
                console.log('video',video)
                video.srcObject = stream;
                video.onloadedmetadata = function () {
                  video.play();
                };
            })
            .catch(function (err) {
                /* 处理 error */
            });
    }

    const closeCam = ()=>{
        setShowPhoto(false)
        // 如果并没有启用摄像头的话 就直接中断
        if(!photoRef.current.srcObject){
             return false
        }
        let stream = photoRef.current.srcObject;
        let tracks = stream.getTracks();
        tracks.forEach( (track:any) => track.stop())
        photoRef.current.srcObject = null


    }
    // 执行拍照
    const takePhoto = ()=>{
        if(photo){
            setPhoto('');
            return false;
        }
        const video = photoRef.current;
        const canvasCtx = canvasRef.current.getContext('2d');
        canvasCtx.drawImage( video,0,0,320,320); // 把video标签的内容绘制到画布上面
        // 把这个图片转成base64字符串
        const photobase64 = canvasRef.current.toDataURL('image/jpeg', 0.7);
        console.log('photobase64', photobase64)
        setPhoto(photobase64)

    }


    return ( 
             <div  className={style.page}>
                    <div className={style.side} style={{ width:`${sideWidth}px` }}>

                      <Tabs items={tabItems} centered />

                       
                       {/* 切换按钮 */}
                        <div className={style.sideBtn} onClick={()=>{ 
                            setSideWidth(sideWidth === 300?0:300)
                        }}></div>
                    </div>
                    <div className={style.main}>
                         <div className={style.maintop}>
                            <Row style={{height:'100%'}} align="middle" gutter={10}>
                                <Col span={3}>
                                    <Button 
                                        size='large'
                                        icon={<i className='iconfont icon-jiahao'></i>}
                                        style={{height:'80%'}}
                                        onClick={()=> setShowAdd(true)}
                                    >新增患者</Button>
                                </Col>
                                <Col span={1}>
                                    <Checkbox  > 欠费 </Checkbox>
                                </Col>
                                <Col span={3}>
                                     <Select  size='large' defaultValue="创建时间" options={ createOption } style={{width:'100%'}} />
                                </Col>
                                <Col span={7}>
                                    <DatePicker.RangePicker  style={{width:'100%'}}  size='large'/>
                                </Col>
                                <Col span={5}>
                                    <Input placeholder='患者姓名/病历号'  size='large' />
                                </Col>
                                <Col span={5}>
                                    <Space>
                                        <Button  size='large'>查询</Button>
                                        <Button  size='large'>重置</Button>
                                        <Button  size='large'>批量操作</Button>
                                    </Space>
                                </Col>
                            </Row>
                         </div>
                         <div className={style.maintable}></div>
                         <div className={style.mainpage}></div>
                    </div>
                    {/* 新增弹窗 */}
                    <Modal
                      forceRender title="新增患者" open={ showAdd } width={1000} onOk={handleAdd}
                      onCancel={()=>setShowAdd(false)}
                      afterOpenChange={ (open:boolean)=> { 
                        if(!open){
                            formRef.setFieldValue('docNo', `${hasPrefix? prefix : ''}${hasDate?dateStr:'' }${ Math.ceil(Math.random()*10000)+1}`)
                        }
                      } }
                    >       
                        <Form size='large'
                              labelCol={{span:4}}
                              form={formRef} 
                        >
                            <div className={style.formTitle}> 基础信息 </div>
                            <Row gutter={75}>
                                <Col span={12}>
                                    <Form.Item name="realName" label="患者姓名" 
                                               rules={[{required: true , message:'患者姓名不能为空' }]}
                                    >
                                        <Input placeholder='请填写患者姓名' />
                                    </Form.Item>
                                    <Form.Item  name="docNo" label="病历号"   rules={[{required: true , message:'病历号不能为空' }]}>
                                    
                                            <Input 
                                                placeholder='请填写病历号'
                                                style={{width:'300px'}}
                                                addonAfter={<>
                                                                <Space>
                                                                    <i className='iconfont icon-xiugai' onClick={()=> setInputBl(false)} ></i>
                                                                    <i className='iconfont icon-shezhi' onClick={()=> setShowSetup(true)} ></i>
                                                                </Space>
                                                            </>
                                                }
                                                disabled={inputBl}
                                            />
                                   
                                    </Form.Item>
                                    <Form.Item name="sex" label="性别"   rules={[{required: true , message:'请选择性别' }]}>
                                        <Radio.Group >
                                            <Radio value="male">男</Radio>
                                            <Radio value="female">女</Radio>
                                        </Radio.Group>
                                    </Form.Item>
                                    <Form.Item name="age" label="年龄">
                                        <Input placeholder='请输入' addonAfter={'岁'} />
                                    </Form.Item>
                                    <Form.Item name="createdAt" label="创建时间">
                                          <DatePicker showTime />
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label="头像上传">
                                         <div className={style.ava}>
                                            <div className={style.preview}>
                                               { photo && <img src={photo} width='100%' height="100%" style={{objectFit:"contain"}} /> }
                                            </div>
                                            <div className={style.btns}> 
                                                      <Button style={{marginBottom:'10px'}} onClick={initCamera}>拍照</Button>
                                                      <Button>上传</Button>
                                            </div>
                                         </div>
                                    </Form.Item>
                                    <Form.Item name="idNo" label="证件">
                                        <Input placeholder='输入您的证件号码' />
                                    </Form.Item>
                                    <Form.Item name="birth" label="出生日期">
                                          <DatePicker showTime />
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form>
                    </Modal>
                    {/* 设置弹窗 */}
                    <Modal open={ showSetup } title="病历号的设置" onOk={()=>setShowSetup(false)} onCancel={()=>setShowSetup(false)}>
                        <div className={style.demo}> 示例： { `${hasPrefix? prefix : ''}${hasDate?dateStr:'' }${countNum}` }  </div>
                        <div className={style.sitem}> 
                             <span className={style.label}>前缀  </span>
                            <Radio.Group  value={hasPrefix} onChange={(ev)=> sethasPrefix(ev.target.value) }>
                                <Radio value={true}>
                                    <div style={{display:'flex',alignItems:'center'}}>
                                           有 <div className={style.no}>QF</div> 
                                    </div>
                                </Radio>
                                <Radio value={false}>无</Radio>
                            </Radio.Group>
                        </div>
                        <div className={style.sitem}> 
                             <span className={style.label}>日期  </span>
                            <Radio.Group  value={hasDate} onChange={(ev)=> sethasDate(ev.target.value) }>
                                <Radio value={true}>有</Radio>
                                <Radio value={false}>无</Radio>
                            </Radio.Group>
                        </div>
                        <div className={style.sitem}> 
                             <span className={style.label}>起始值  </span>
                             <div style={{display:'flex',alignItems:'center'}}>
                                <span>从</span>
                                <InputNumber value={startNum} min={1} style={{margin:'0 5px'}} onChange={(val)=> setStartNum(val as number)} />
                                <span>开始</span>
                             </div>
                            
                        </div>
                    </Modal>
                    <Modal
                        title="拍照" 
                        open={ showPhoto } 
                        forceRender
                        onCancel={ closeCam }
                        footer={ 
                            <> 
                             <Button onClick={takePhoto}> { photo ? '重排':'拍照'} </Button>
                             <Button disabled={ photo?false:true } onClick={closeCam}>确定</Button>
                            </> 
                        }
                    >
                        <div className={style.photo}>
                            <video width="100%" height="100%" ref={ photoRef } style={{objectFit:'cover',display: photo ? 'none':'block'}}></video>
                            <canvas ref={canvasRef} style={{display: photo ? 'block':'none'}}></canvas>
                        </div>
                    </Modal>


             </div> 
    )
            
}

export default  Patient